package com.kermel.andromeda.data.settings;

import android.content.Context;
import android.content.SharedPreferences;

import com.kermel.andromeda.data.DateDisplayType;
import com.kermel.andromeda.data.settings.ClockSettings;

public class ClockSettingsPersister {
    public static final String SETTINGS_NAME = "ClockSettings";
    
    public static final String MILITARY_TIME = "militaryTime";
    public static final String DISPLAY_SECONDS = "displaySeconds";
    public static final String DISPLAY_DATE = "displayDate";
    public static final String DATE_DISPLAY_TYPE = "dateDisplayType";
    
    private SharedPreferences sharedPrefs;
    
    public ClockSettingsPersister(Context context) {
        sharedPrefs = context.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);
    }
    
    public boolean store(ClockSettings settings) {
        boolean result = false;
        
        if (settings != null && sharedPrefs != null) {
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putBoolean(MILITARY_TIME, settings.isMilitaryTime());
            editor.putBoolean(DISPLAY_SECONDS, settings.isDisplaySeconds());
            editor.putBoolean(DISPLAY_DATE, settings.isDisplayDate());
            DateDisplayType dateDisplayType = settings.getDateDisplayType();
            if (dateDisplayType != null)
                editor.putString(DATE_DISPLAY_TYPE, dateDisplayType.name());
            result = editor.commit();
        }
        
        return result;
    }
    
    public boolean retrieve(ClockSettings settings) {
        boolean result = false;
        
        if (settings != null && sharedPrefs != null) {
            settings.militaryTime = sharedPrefs.getBoolean(MILITARY_TIME, false);
            settings.displaySeconds = sharedPrefs.getBoolean(DISPLAY_SECONDS, false);
            settings.displayDate = sharedPrefs.getBoolean(DISPLAY_DATE, false);
            result = updateDateDisplayType(settings);
        }
        
        return result;
    }
    
    private boolean updateDateDisplayType(ClockSettings settings) {
        boolean result = false;
        
        String dateDisplayTypeValue = sharedPrefs.getString(DATE_DISPLAY_TYPE, null);
        if (dateDisplayTypeValue != null) {
            try {
                settings.dateDisplayType = DateDisplayType.valueOf(dateDisplayTypeValue);
                result = true;
            } catch (Exception e) {
                // Intentionally ignored; may want to log it, however.
            }
        }
        
        return result;
    }
    
}
